﻿using System.Net;
using System.Web.Routing;
using EmailSender.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Web;
using System.Web.Mvc;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using Mn.Framework.Service.Messaging;

namespace EmailSender.Controllers
{
    public class SendEmailController : Controller
    {
        private int itemsCount = 80;
        private readonly EmailContext _db = new EmailContext();
        //
        // GET: /SendEmail/

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Index(int catId = 0)
        {
            ViewBag.Categories = _db.Categories.ToList();
            ViewBag.SmtpServers = _db.SmtpServer.ToList();
            ViewBag.SmtpCredentials = _db.SmtpCredential.ToList();

            var model = new SendEmailModel { CategoryId = catId };

            return View(model);
        }

        public ActionResult ImageBrowser()
        {
            return View();
        }

        [HttpPost, ValidateInput(false)]
        public string Send(SendEmailModel sendEmailModel)
        {
            try
            {
                var emailList = sendEmailModel.EmailAddress.Split(',')
                    .Select(email => email.Trim())
                    .Where(email => !string.IsNullOrEmpty(email)).ToList();
                var smtpServer = _db.SmtpServer.SingleOrDefault(ss => ss.ID == sendEmailModel.SmtpServerId);
                var mailUser = _db.SmtpCredential.SingleOrDefault(c => c.ID == sendEmailModel.SmtpCredentialId);
                var mailServer = new SmtpServer()
                {
                    HostAddress = smtpServer.SmtpAddress,
                    Port = smtpServer.Port.HasValue ? smtpServer.Port.Value : 25,
                    Username = mailUser.UserName,
                    Password = mailUser.Password
                };

                string resultMessage;
                if (new MailSender(mailServer, mailUser.EmailFrom)
                    .SendBcc(emailList, sendEmailModel.Subject, sendEmailModel.Body, out resultMessage))
                {
                    resultMessage =
                        string.Format(@"ارسال با موفقیت انجام شد.  دسته بندی{0} . ایمیل های ارسالی از ردیف {1} به بعد",
                            sendEmailModel.CategoryId, sendEmailModel.SkipCount);
                }
                else
                    resultMessage = "خطا در ارسال ایمیل " + resultMessage;

                return resultMessage;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        public ActionResult EmailAddress_Read([DataSourceRequest]DataSourceRequest request, int categoryId, int skipCount)
        {
            if (categoryId == 0)
                return Json(_db.EmailAddress.OrderBy(e => e.ID).Skip(skipCount).Take(itemsCount).ToDataSourceResult(request));
            else
            {
                return Json(_db.EmailAddress.Where(email => email.EmailCategory.Any(ec => ec.CatId == categoryId))
                    .OrderBy(e => e.ID).Skip(skipCount).Take(itemsCount).ToDataSourceResult(request));
            }
        }       

    }
}
